// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <nebula/util/counting_semaphore.h>

#include <atomic>
#include <thread>
#include <vector>

#include <nebula/testing/ktest_util.h>
#include <nebula/version.h>
#include <ktest/ktest.h>

namespace nebula {
namespace util {

TEST(CountingSemaphore, Basic) {

  CountingSemaphore semaphore;
  std::atomic<bool> acquired{false};
  std::atomic<bool> started{false};
  std::thread acquirer([&] {
    started.store(true);
    ASSERT_OK(semaphore.Acquire(3));
    acquired = true;
  });
  ASSERT_OK(semaphore.WaitForWaiters(1));
  ASSERT_TRUE(started.load());
  ASSERT_FALSE(acquired.load());
  ASSERT_OK(semaphore.Release(2));
  SleepABit();
  ASSERT_FALSE(acquired.load());
  ASSERT_OK(semaphore.Release(1));
  BusyWait(10, [&] { return acquired.load(); });
  ASSERT_TRUE(acquired.load());
  ASSERT_OK(semaphore.close());
  acquirer.join();
}

TEST(CountingSemaphore, CloseAborts) {

  CountingSemaphore semaphore;
  std::atomic<bool> cleanup{false};
  std::thread acquirer([&] {
    ASSERT_RAISES(turbo::StatusCode::kInvalidArgument, semaphore.Acquire(1));
    cleanup = true;
  });
  ASSERT_OK(semaphore.WaitForWaiters(1));
  ASSERT_FALSE(cleanup.load());
  ASSERT_RAISES(turbo::StatusCode::kInvalidArgument, semaphore.close());
  BusyWait(10, [&] { return cleanup.load(); });
  acquirer.join();
}

TEST(CountingSemaphore, Stress) {

  constexpr uint32_t NTHREADS = 10;
  CountingSemaphore semaphore;
  std::vector<uint32_t> max_allowed_cases = {1, 3};
  std::atomic<uint32_t> count{0};
  std::atomic<bool> max_exceeded{false};
  std::vector<std::thread> threads;
  for (uint32_t max_allowed : max_allowed_cases) {
    ASSERT_OK(semaphore.Release(max_allowed));
    for (uint32_t i = 0; i < NTHREADS; i++) {
      threads.emplace_back([&] {
        ASSERT_OK(semaphore.Acquire(1));
        uint32_t last_count = count.fetch_add(1);
        if (last_count >= max_allowed) {
          max_exceeded.store(true);
        }
        SleepABit();
        count.fetch_sub(1);
        ASSERT_OK(semaphore.Release(1));
      });
    }
    for (auto& thread : threads) {
      thread.join();
    }
    threads.clear();
    ASSERT_OK(semaphore.Acquire(max_allowed));
  }
  ASSERT_OK(semaphore.close());
  ASSERT_FALSE(max_exceeded.load());
}

}  // namespace util
}  // namespace nebula
